package com.fenghongzhang.module_user.db

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.fenghongzhang.module_Teacher.dao.TeacherDao
import com.fenghongzhang.module_user.dao.UserDao
import com.fenghongzhang.module_user.model.Teacher
import com.fenghongzhang.module_user.model.User


@Database(entities = [User::class, Teacher::class], version = 2, exportSchema = false)
abstract class AppDatabase : RoomDatabase() {
    abstract fun userDao(): UserDao
    abstract fun teacherDao(): TeacherDao


    companion object {

        val MIGRATION_1_2: Migration = object : Migration(1, 2) {
            override fun migrate(database: SupportSQLiteDatabase) {
                // 1. 检查旧表是否存在
                val cursor =
                    database.query("SELECT name FROM sqlite_master WHERE type='table' AND name='Teacher'")
                val tableExists = cursor.count > 0
                cursor.close()

                if (tableExists) {
                    // 旧表存在：执行重建表逻辑
                    database.execSQL("CREATE TABLE Teacher_temp (uid INTEGER PRIMARY KEY NOT NULL, first_name TEXT, last_name TEXT)")
                    database.execSQL("INSERT INTO Teacher_temp (uid, first_name, last_name) SELECT uid, first_name, last_name FROM Teacher")
                    database.execSQL("DROP TABLE Teacher")
                    database.execSQL("ALTER TABLE Teacher_temp RENAME TO Teacher")
                } else {
                    // 旧表不存在：直接创建新表（首次安装或旧表已删除）
                    database.execSQL(
                        "CREATE TABLE Teacher (uid INTEGER PRIMARY KEY NOT NULL, first_name TEXT, last_name TEXT)"
                    )
                }
            }
        }

        @Volatile
        private var INSTANCE: AppDatabase? = null

        fun getDatabase(context: Context): AppDatabase {
            return INSTANCE ?: synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    AppDatabase::class.java,
                    "a2207"
                ).allowMainThreadQueries()
                    .addMigrations(MIGRATION_1_2)
                    .build()
                INSTANCE = instance
                instance
            }
        }
    }

}